﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace eCRAM.Tools
{
    /// <summary>
    /// Represente une pile circulaire
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CircularStack<T>
    {
        /// <summary>
        /// Liste des élements sur lesquels on itére
        /// </summary>
        private readonly T[] _items;

        /// <summary>
        /// Index du prochain élement à retourner
        /// </summary>
        private int _currentIndex;

        /// <summary>
        /// Constructeur
        /// </summary>
        /// <param name="items"></param>
        public CircularStack(params T[] items)
        {
            if (items == null || items.Length == 0)
            {
                throw new ArgumentException("Items cannot be null or empty.");
            }
            _items = items;
        }

        /// <summary>
        /// Constructeur
        /// </summary>
        /// <param name="items"></param>
        public CircularStack(IEnumerable<T> items)
        {
            if (items == null || items.Count() == 0)
            {
                throw new ArgumentException("Items cannot be null or empty.");
            }
            _items = items.ToArray();
        }

        /// <summary>
        /// Obtient l'élement suivant dans la pile
        /// </summary>
        /// <returns></returns>
        public T GetNextItem()
        {
            if(_currentIndex >= _items.Length)
            {
                _currentIndex = 0;
            }

            return _items[_currentIndex++];
        }

        /// <summary>
        /// Positionne l'index de la liste
        /// </summary>
        /// <param name="index"></param>
        public void SetIndex(int index)
        {
            if (index >= _items.Length)
            {
                throw new ArgumentException("Index cannot be greater than items count.");
            }

            _currentIndex = index;
        }
    }
}
